﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using wp7cinema.Model;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.IO;

namespace wp7cinema.ViewModel
{
    public struct Point
    {
        public string Title { get; set; }
        public float StarPoint { get; set; }
    }
    public class MovieDetailModelView : ViewModelBase
    {
        public MovieSimpleInfo _movieSimpleInfo;
        public MovieSimpleInfo MovieSimpleInfo
        {
            get { return _movieSimpleInfo; }
            set
            {
                _movieSimpleInfo = value;
                RaisePropertyChanged("MovieSimpleInfo");
            }
        }
        public IEnumerable<Point> _points;
        public IEnumerable<Point> Points
        {
            get { return _points; }
            set
            {
                _points = value;
                RaisePropertyChanged("Points");
            }
        }

        public MovieDetailModelView()
        {
            if (IsInDesignMode)
            {
                MovieSimpleInfo = new MovieSimpleInfo
                {
                    Description = "드림머신이라는 기계로 타인의 꿈과 접속해 생각을 빼낼 수 있는 미래사회.‘돔 코브..",
                    DetailViewCode = "52515",
                    Genre = "SF",
                    ImgUrl = "http://imgmovie.naver.com/mdi/mit500/0525/52515_P31_095232.jpg",
                    Point = "9.15",
                    PreorderCode = "52515",
                    ReleaseDay = "2010.07.21",
                    Runtime = "147",
                    ShareRate = "75.5",
                    Title = "인셉션"
                };
                Points = new ObservableCollection<Point> {
                    new Point { StarPoint=5, Title="마무리가 좀 구린거빼면 존나재밌음." },
                    new Point { StarPoint=9.8f, Title="매끄럽지 못한 류승범 연기 ,,영화의 흐름을 방해 하는 것 같았다.나름 괜찮음" },
                    new Point { StarPoint=5, Title="지루하고 뻔하다  역시 류승완... 짝패보단낫다  글고 알바작렬인듯" },
                    new Point { StarPoint=7, Title="마무리가 좀 구린거빼면 존나재밌음." },
                    new Point { StarPoint=6, Title="마무리가 좀 구린거빼면 존나재밌음." },
                    new Point { StarPoint=5.5f, Title="마무리가 좀 구린거빼면 존나재밌음." },
                    new Point { StarPoint=4, Title="마무리가 좀 구린거빼면 존나재밌음." },
                    new Point { StarPoint=3, Title="마무리가 좀 구린거빼면 존나재밌음." }
                };
            }
            else
            {
                MovieSimpleInfo = App.Current.Resources["MovieSimpleInfo"] as MovieSimpleInfo;

                string url = "http://movie.naver.com/movie/bi/mi/point.nhn?code=" + MovieSimpleInfo.DetailViewCode;
                //url = "http://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword=73344&target=after&page=2";
                url = "http://ailab.jnu.ac.kr/socket/test.php?sword=" + MovieSimpleInfo.DetailViewCode;
                WebClient client = new WebClient();
                //client.OpenReadAsync(new Uri(url));
                //client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                client.DownloadStringCompleted += PointPageDownloadCompleted;
                client.DownloadStringAsync(new Uri(url));
            }
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream stream = e.Result;
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            string aa = str;
        }

        void PointPageDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html = e.Result;

            StringBuilder builder = new StringBuilder();
            builder.Append("(<td class=\"point\">)([0-9]{1,2})(</td>)([\n\r\t]+)");
            builder.Append("(<td class=\"title\">)([\n\r\t]+)");
            builder.Append("(<a href=\"/movie/bi/mi/basic.nhn\\?code=[0-9]{2,10}\" class=\"movie\">.{2,30}</a>)");
            builder.Append("([\n\r\t]+<br>)(.{2,50})([\r\n]+)");

            MatchCollection matches = Regex.Matches(html, builder.ToString());

            ObservableCollection<Point> points = new ObservableCollection<Point>();
            float starPoint;
            foreach (Match m in matches)
            {
                starPoint = Convert.ToSingle(m.Groups[2].Value);
                points.Add(new Point { StarPoint = starPoint, Title = m.Groups[9].Value });
            }
            Points = points;
        }
    }
}